import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/constants/app_constants.dart';
import '../../core/utils/content_filter.dart';

/// 内容过滤Provider
/// 管理内容过滤级别设置
class ContentFilterProvider extends ChangeNotifier {
  FilterLevel _filterLevel = FilterLevel.basic;
  late SharedPreferences _prefs;
  bool _isInitialized = false;

  FilterLevel get filterLevel => _filterLevel;
  bool get isInitialized => _isInitialized;

  /// 初始化设置
  Future<void> init() async {
    if (_isInitialized) return;
    
    _prefs = await SharedPreferences.getInstance();
    await _loadFilterLevel();
    _isInitialized = true;
  }

  /// 加载保存的过滤级别
  Future<void> _loadFilterLevel() async {
    final levelIndex = _prefs.getInt(AppConstants.contentFilterKey) ?? 1; // 默认基础过滤
    if (levelIndex >= 0 && levelIndex < FilterLevel.values.length) {
      _filterLevel = FilterLevel.values[levelIndex];
    } else {
      _filterLevel = FilterLevel.basic;
    }
    notifyListeners();
  }

  /// 设置过滤级别
  Future<void> setFilterLevel(FilterLevel level) async {
    if (_filterLevel == level) return;
    
    _filterLevel = level;
    await _prefs.setInt(AppConstants.contentFilterKey, level.index);
    notifyListeners();
  }

  /// 获取当前过滤级别的中文描述
  String get filterLevelDescription {
    return ContentFilter.getFilterLevelDescription(_filterLevel);
  }

  /// 检查动漫是否应该被过滤
  bool shouldFilterAnime(
    String? rating,
    List<String> genres,
    String title,
    String synopsis,
  ) {
    return ContentFilter.isAdultContent(
      rating,
      genres,
      title,
      synopsis,
      level: _filterLevel,
    );
  }

  /// 过滤动漫列表
  List<T> filterAnimeList<T>(
    List<T> animeList,
    String? Function(T) getRating,
    List<String> Function(T) getGenres,
    String Function(T) getTitle,
    String Function(T) getSynopsis,
  ) {
    return ContentFilter.filterAnimeList(
      animeList,
      _filterLevel,
      getRating,
      getGenres,
      getTitle,
      getSynopsis,
    );
  }

  /// 获取所有过滤级别选项
  List<FilterLevel> get allFilterLevels {
    return ContentFilter.getAllFilterLevels();
  }
} 